package eaa.tgi.scrum.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import eaa.tgi.scrum.constants.ControllerConstants;
import eaa.tgi.scrum.domain.Message;
import eaa.tgi.scrum.domain.User;

@Controller
public class ChatController {
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(ControllerConstants.HANDLE_CHAT)
	public ModelAndView displayChat(HttpServletRequest request) {
		
		ModelAndView modelView = new ModelAndView(ControllerConstants.JSP_CHAT);
		modelView.getModelMap().addAttribute("messageToBeSent", new Message());
		
		
		return modelView;
	}
	
	@RequestMapping(ControllerConstants.HANDLE_USER_LIST)
	public ModelAndView displayUsers(HttpServletRequest request) {
		
		ModelAndView modelView = new ModelAndView();
		
		User user = (User) request.getSession().getAttribute("authenticatedUser");
		
		List<User> users = user.getProject().getUsers();
		modelView.addObject("projectUsers", users);
		
		modelView.setViewName(ControllerConstants.JSP_USER_LIST);
		return modelView;
	}
	
	@RequestMapping(ControllerConstants.HANDLE_MESSAGES)
	public ModelAndView displayMessages(HttpServletRequest request) {
		
		ModelAndView modelView = new ModelAndView(ControllerConstants.JSP_MESSAGES);
		
		User user = (User) request.getSession().getAttribute("authenticatedUser");
		
		List<Message> messages = user.getProject().getMessages();
		modelView.addObject("projectMessages", messages);
		
		return modelView;
	}
	
	
	@RequestMapping(ControllerConstants.HANDLE_SEND_MESSAGE)
	public ModelAndView sendMessage(HttpServletRequest request) {
		
		ModelAndView modelView = new ModelAndView();
		
		User user = (User) request.getSession().getAttribute("authenticatedUser");
		
		Message messageToBeStored = new Message();
		messageToBeStored.setUser(user);
		messageToBeStored.setProject(user.getProject());
		messageToBeStored.setMessage(request.getParameter("msg"));
		
		user.getProject().receiveMessage(messageToBeStored);
		
		return modelView;
	}
}
